<template>
  <!--
    根目录规范(必须不能为空)：
    idm-ctrl：控件类型 drag_container：容器，drag_container_inlieblock：行内容器，idm_module：非容器的组件
    id：使用moduleObject.id，如果id不使用这个将会被idm-ctrl-id属性替换
    idm-ctrl-id：组件的id，这个必须不能为空
  -->
  <div idm-ctrl="idm_module"
  :id="moduleObject.id"
  :idm-ctrl-id="moduleObject.id"
  >
    <div class="chartImage-wrap" :style="propData.isHeightType && moduleHeight ? { height: moduleHeight, width: propData.width } : { height: propData.height, width: propData.width }">
      <div class="writiTitle" v-if="propData && propData.isTips" ref="writiTop">
        <div class="chart-tab">{{ propData && propData.titleDesc }}</div>
        <div
          v-show="propData.isBlock"
          class="chart-idm-dragbox"
          :style="{ left: propData.dragContainerX, top: propData.dragContainerY }"
        >
          <div
            class="drag_container"
            idm-ctrl-inner
            :idm-ctrl-id="moduleObject.id"
            idm-container-index="1"
          ></div>
        </div>
      </div>
      <div class="chartImage-center">
        <div class="chart-li" v-for="(item, index) in propData && (propData.tableMenu)" :key="index" :style="computedStyle(item)" @click="handleClick(item, index)">
          <div class="chart-left" v-if="propData.isImage" :style="`width:${item.imageWidth};height:${item.imageHeight};margin-right:${item.imageRight};margin-bottom:${item.imageBottom}`">
            <img :src="getBackImgSrc(item, index)" alt="">
          </div>
          <div class="chart-right">
            <div class="chart-title" :style="computedTitle(item)" >{{handleTitle(item, index)}}</div>
            <div class="chart-num" :style="computedSub(item)">
              <span>{{handleTitleSub(item, index)}}</span>
              <template v-if="!item.showStyle">
                <span :style="computedGeSub(item)">{{item.titleType}}</span>
              </template>
              <template v-if="item.showStyle=='1'">
                <span :style="computedGeSub(item)">{{item.titleType}}</span>
              </template>
              <template v-if="item.showStyle=='2'">
                <i :style="computedLine(item)">/</i>
                <span :style="computedGeSub(item)">{{handleSetFont(item, index)}}</span>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'IchartImage',
  data () {
    return {
      fieldObj: [],
      moduleObject:{},
      inforobj: {},
      moduleHeight: '',
      messageAll: {},
      cacheObj: {},
      propData:this.$root.propData.compositeAttr || {
        isHeightType: true,
        height: '200px',
        isImage: true,
        isTips: true,
        titleDesc: '风险管控',
        showType: '1',
        contentLayout: {
          display: "flex",
          direction: "row",
          align: "center",
          justify: "center"
        },
        tableMenu: []
      },
      list: []
    }
  },
  mounted () {
    this.moduleObject = this.$root.moduleObject;
    this.init();
    this.$nextTick(() => {
      this.resizeContentWrapperHeight()
    })
  },
  methods: {
    getBackImgSrc(item, index) {
      if (!this.moduleObject.env) {
        let { image } = item;
        return image
      }
      if (item.imageField && this.moduleObject.env == "production") {
        return (this.fieldObj[index] || {})[item.imageField];
      }
      let { image } = item;
      return image ? IDM.url.getWebPath(image) : '';
    },
    handleTitle (item, index) {
      if (item.titleField && this.moduleObject.env == "production") {
        return (this.fieldObj[index] || {})[item.titleField]
      }
      return item.title
    },
    handleTitleSub (item, index) {
      if (item.numField && this.moduleObject.env == "production") {
        return (this.fieldObj[index] || {})[item.numField];
      }
      return item.titleSub
    },
    handleSetFont (item, index) {
      if (item.denominaField && this.moduleObject.env == "production") {
        return (this.fieldObj[index] || {})[item.denominaField];
      }
      return item.denominator
    },
    computedStyle (item) {
      let {libox, border, bgColor, liWidth, liHeightbox, backgroundImage} = item;
      let style = {};
      if (liWidth) {
        style['width'] = liWidth;
        liHeightbox && (style['height'] = liHeightbox);
      }
      if (libox) {
        IDM.style.setBoxStyle(style, libox)
      }
      if (border) {
        IDM.style.setBorderStyle(style, border)
      }
      if (bgColor) {
        style['background-color'] = bgColor && bgColor.hex8
      }
      if (backgroundImage) {
        let imageurl = IDM.url.getWebPath(backgroundImage);
        style['background-image'] = `url(${imageurl})`;
        style['background-repeat'] = 'no-repeat';
        style['background-size'] = '100% 100%';
      }
      return style;
    },
    computedTitle (item) {
      let {titleBottom, titleFont} = item;
      let style = {}
      if (titleBottom) {
        style['margin-bottom'] = titleBottom;
      }
      if (titleFont) {
        IDM.style.setFontStyle(style, titleFont);
      }
      return style;
    },
    computedLine(item) {
      let {lineBgColor, linePd, lineSize} = item;
      let style = {}
      if (lineBgColor) {
        style['color'] = lineBgColor && lineBgColor.hex8
      }
      if (lineSize) {
        style['font-size'] = lineSize
      }
      if (linePd) {
        style['padding'] = `0 ${linePd}`;
      }
      return style;
    },
    computedSub (item) {
      let {subFont} = item;
      let style = {}
      if (subFont) {
        IDM.style.setFontStyle(style, subFont);
      }
      return style;
    },
    computedGeSub (item) {
      let {geFont, unitMarLeft} = item;
      let style = {}
      if (geFont) {
        IDM.style.setFontStyle(style, geFont);
      }
      if (unitMarLeft) {
        style['margin-left'] = unitMarLeft
      }
      return style;
    },
    propDataWatchHandle (propData) {
      this.propData = propData.compositeAttr || {};
      this.init();
    },
    handleStyle () {
      let styleObject = {},
        liStyle = {},
        lichart = {},
        contentObject = {},
        lineStyle = {},
        tipsStyleObj = {};
      for (const key in this.propData) {
        if (this.propData.hasOwnProperty.call(this.propData, key)) {
          const element = this.propData[key]
          if (!element && element !== false && element != 0) {
              continue
          }
          switch (key) {
            case 'width':
              styleObject['width'] = element
              break
            case 'height':
              styleObject['height'] = element;
              break
            case 'ulbox':
              IDM.style.setBoxStyle(styleObject, element)
              break
            case 'bgColor':
              styleObject['background-color'] = element && element.hex8
              break
            case 'boxShadow':
              styleObject['box-shadow'] = element
              break
            case 'boxborder':
              IDM.style.setBorderStyle(styleObject, element)
              break
            case 'tipsBox':
              IDM.style.setBoxStyle(tipsStyleObj, element)
              break
            case 'tipsBorder':
              IDM.style.setBorderStyle(tipsStyleObj, element)
              break
            case 'tipsFont':
              IDM.style.setFontStyle(tipsStyleObj, element, true);
              break
            case 'showType':
              if (element == '1') {
                liStyle['display'] = 'flex';
                liStyle['float'] = 'left';
                liStyle['align-items'] = 'center';
                if (this.propData.isCenter) {
                  lichart['text-align'] = 'center';
                }
                // liStyle['flex-direction'] = 'column';
              } else if (element == '2') {
                liStyle['display'] = 'flex';
                liStyle['float'] = 'left';
                liStyle['align-items'] = 'center';
                liStyle['justify-content'] = 'center';
                liStyle['flex-direction'] = 'column'
                lichart['text-align'] = 'center';
              }
              break
            case 'contentLayout':
              if (element.display && element.display == "flex") {
                contentObject['flex-wrap'] = "wrap";
                contentObject['display'] = 'flex';
                if (element.direction) {
                  contentObject["flex-direction"] = element.direction;
                }
                if (element.align) {
                  contentObject["align-items"] = element.align;
                }
                if (element.justify) {
                  contentObject["justify-content"] = element.justify;
                }
              } else if (element.display) {
                contentObject["display"] = element.display;
              }
              break
            case 'isTitleShow':
              if (element) {
                lineStyle['bottom'] = this.propData.titlepostion;
                lineStyle['background-color'] = this.propData.titleLineColor && this.propData.titleLineColor.hex8 + ' !important';
              } else {
                lineStyle['height'] = 0;
              }
              break
          }
        }
      }
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .chartImage-wrap", styleObject);
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .chartImage-center", contentObject);
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .chart-li", liStyle);
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .chart-li .chart-right", lichart);
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .writiTitle", tipsStyleObj);
      window.IDM.setStyleToPageHead(this.moduleObject.id + " .writiTitle .chart-tab::after", lineStyle);
    },
    // 过滤接口参数
    fileterParams() {
      let obj = {};
      if (this.propData.customFunc && this.propData.customFunc.length > 0) {
        let name = this.propData.customFunc[0].name
        obj = window[name] && window[name].call(this, this.inforobj, this.propData.dictRule, this.cacheObj, this.messageAll);
      }
      this.cacheObj = obj;
      return obj
    },
    initData () {
      if (!this.moduleObject.env) {
        this.propData.tableMenu = [
          {
            key: "1",
            liWidth: "24%",
            liHeightbox: "auto",
            title: "提交",
            titleSub: "1",
            titleType: "个",
            image: require('../assets/type1.png'),
            imageWidth: '60px',
            imageHeight: '60px',
            imageRight: '10px',
            unitMarLeft: '5px',
            denominator: '94',
            lineBgColor: {
              hex8: '#f00'
            },
            linePd: '4px',
            lineSize: '16px'
          },
          {
            key: "1",
            liWidth: "24%",
            liHeightbox: "auto",
            title: "提交",
            titleSub: "1",
            titleType: "个",
            image: require('../assets/type1.png'),
            imageWidth: '60px',
            imageHeight: '60px',
            imageRight: '10px',
            unitMarLeft: '5px',
            denominator: '94',
            lineBgColor: {
              hex8: '#f00'
            },
            linePd: '4px',
            lineSize: '16px'
          }
        ]
      }
      if (this.moduleObject.env == "production") {
        this.list = this.propData && (this.propData.tableMenu || []);
        if (this.propData.isField && this.propData.dataSource) {
          const routerParams = this.fileterParams();
          if(routerParams && routerParams._break){ // 如果_break=true，则不请求接口
            return false;
          }
          IDM.datasource.request(this.propData.dataSource[0]?.id, {
            moduleObject: this.moduleObject,
            param: { ...routerParams }
          }, (data) => {
            if (data) {
              if (this.propData.responseFunc && this.propData.responseFunc.length > 0) {
                let name = this.propData.responseFunc[0].name;
                let obj = window[name] && window[name].call(this, { response: data, param: routerParams });
                if (obj instanceof Array) {
                  this.propData.tableMenu = this.propData.tableMenu.slice(0, obj.length);
                  this.fieldObj = obj;
                } else {
                  console.warn('接口返回必须是数组');
                }
              } else {
                if (data instanceof Array) {
                  this.propData.tableMenu = this.propData.tableMenu.slice(0, data.length);
                  this.fieldObj = data;
                } else {
                  console.warn('接口返回必须是数组');
                }
              }
            }
          })
        }
      } else {
        this.list = this.propData && (this.propData.tableMenu || []);
      }
    },
    // 主题
    convertThemeListAttrToStyleObject() {
      let themeList = this.propData.themeList;
      if (!themeList) {
        return;
      }
      const themeNamePrefix =
        IDM.setting &&
        IDM.setting.applications &&
        IDM.setting.applications.themeNamePrefix
          ? IDM.setting.applications.themeNamePrefix
          : "idm-theme-";
      for (let i=0; i<themeList.length; i++) {
        let item = themeList[i]
        if(item.key!=IDM.theme.getCurrentThemeInfo()){
            //此处比对是不渲染输出不用的样式，如果页面会刷新就可以把此处放开
            continue;
        }
        let tempobj = {},
          lineobj = {};
        tempobj = {
          "color": item.mainColor ? item.mainColor.hex8 : "",
        }
        lineobj = {
          "background-color": item.mainColor ? item.mainColor.hex8 : "",
        }
        IDM.setStyleToPageHead(
          `.${themeNamePrefix}${item.key} #${(this.moduleObject.id || "module_demo")} .writiTitle`,
          tempobj
        );
        IDM.setStyleToPageHead(
          `.${themeNamePrefix}${item.key} #${(this.moduleObject.id || "module_demo")} .writiTitle .chart-tab:after`,
          lineobj
        );
      }
    },
    init () {
      console.log(this.propData, '数据源');
      this.handleStyle();
      this.propData.initLoad && this.initData();
      this.convertThemeListAttrToStyleObject()
    },
    handleClick (item, index) {
      let { jumpUrl } = item;
      if (jumpUrl) {
        let url = '';
        if (this.fieldObj[index]) {
          url = this.fieldObj[index][jumpUrl]
        } else {
          url = jumpUrl
        }
        window.location.href = url;
        return;
      }
      if (this.propData.jumpFun && this.propData.jumpFun.length > 0) {
        let name = this.propData.jumpFun[0].name;
        window[name] && window[name].call(this, item, this.inforobj, this.propData.dictRule, this.fieldObj[index]);
      }
    },
    /**
     * 组件通信：接收消息的方法
     * @param {
     *  type:"发送消息的时候定义的类型，这里可以自己用来要具体做什么，统一规定的type：linkageResult（组件联动传结果值）、linkageDemand（组件联动传需求值）、linkageReload（联动组件重新加载）
     * 、linkageOpenDialog（打开弹窗）、linkageCloseDialog（关闭弹窗）、linkageShowModule（显示组件）、linkageHideModule（隐藏组件）、linkageResetDefaultValue（重置默认值）"
     *  message:{发送的时候传输的消息对象数据}
     *  messageKey:"消息数据的key值，代表数据类型是什么，常用于表单交互上，比如通过这个key判断是什么数据"
     *  isAcross:如果为true则代表发送来源是其他页面的组件，默认为false
     * } object
     */
    receiveBroadcastMessage(object) {
      switch (object.type) {
        case 'linkageDemand':
          console.log('IwritiShow接收消息: ', object.message)
          this.inforobj = object.message;
          this.messageAll = object;
          this.initData();
          break;
          // 高度适应
        case 'regionResize':
          if (object.message && object.message.gridEleTarget) {
            let gridEleTarget = object.message.gridEleTarget
            if (gridEleTarget && gridEleTarget.offsetHeight) {
                this.resizeContentWrapperHeight(gridEleTarget.offsetHeight)
            }
          }
          break
        case this.propData.getKey:
          console.log('接收消息key的信息', object.message);
          this.inforobj = object.message;
          this.messageAll = object;
          this.initData();
        break;
      }
    },
    // 当外部容器改变时，改变组件高度，改变文字大小
    resizeContentWrapperHeight (wrapperHeight) {
      let moduleHeight = this.propData.isHeightType
          ? $('#' + this.moduleObject.packageid)
              .parents('.fsl-region-element')
              .height()
          : this.propData.height;

      // let moduleHeight = "";
      if (this.propData.isHeightType) {
          //自适应父级容器
          moduleHeight = wrapperHeight || moduleHeight + 'px';
      }
      this.moduleHeight = moduleHeight;
      if (this.propData.isHeightType && this.$refs['writiTop']) {
        let topHeight = this.$refs['writiTop'],
        reduceHei = topHeight.offsetHeight;
        let contentHei = {};
        contentHei['height'] = `calc(100% - ${reduceHei}px)`
        window.IDM.setStyleToPageHead(this.moduleObject.id + " .chartImage-wrap .chartImage-center", contentHei);
      }
    },
    /**
     * 把组件的属性传递给开发环境的组件属性中
     * attrData:{attrKey1,attrKey2}  要变更的属性对象
     * attrDataInnerIndex:属性对应的类型，默认为-1是组件属性，如果为组件内部的容器属性，则需要传指定容器的idm-container-index
     */
    setPropDataToDevelopAttrData(attrData,attrDataInnerIndex){
      IDM.develop&&IDM.develop.externalMixAttributeChangeHandle(attrData,this.moduleObject.packageid,attrDataInnerIndex,false)
    }
  }
}
</script>

<style lang="scss" scoped>
.chartImage-wrap{
  // display: flex;
  // flex-wrap: wrap;
  overflow: hidden;
  box-sizing: border-box;
  .writiTitle{
    display: flex;
    justify-content: space-between;
    .chart-tab{
      display: inline-block;
      position: relative;
    }
    .chart-tab::after{
      content: "";
      width: 100%;
      height: 2px;
      border-radius: 2px;
      position: absolute;
      left: 0;
    }
  }
  .chart-idm-dragbox{
    min-height: 20px;
    position: absolute;
    top: 0;
    left: 0;
  }
  .chart-li{
    // display: flex;
    // flex: 1;
    // float: left;
    // align-items: center;
    // justify-content: center;
    .chart-left img{
      width: 100%;
      height: 100%;
    }
  }
}
</style>
